import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, FormGroup} from "@angular/forms";
import {Purpose} from "../../shared/model/purpose";
import {UdgTableComponent} from "../../shared/component/udg-table/udg-table.component";
import {FileUploadComponent} from "../../shared/component/file-upload/file-upload.component";
import {CamApplyService} from "../../shared/service/cam-apply.service";
declare var $:any;

@Component({
  selector: 'app-cam-apply-by-user',
  templateUrl: './cam-apply-by-user.component.html',
  styleUrls: ['./cam-apply-by-user.component.css']
})
export class CamApplyByUserComponent implements OnInit {

  _checked = true;
  saveFlag = true;  //防止重复提交
  userId:string = this.routerInfo.snapshot.queryParams["userId"];
  flag:string = this.routerInfo.snapshot.queryParams["flag"];
  // userId:string ="004";
  camForm:FormGroup;
  purposes:Purpose[];
  @ViewChild(UdgTableComponent) udgTable :UdgTableComponent;
  @ViewChild(FileUploadComponent) child :FileUploadComponent;

  constructor(
    private router:Router,
    private routerInfo:ActivatedRoute,
    private fb:FormBuilder,
    private camApplyService:CamApplyService
  ) { }

  ngOnInit() {
    this.saveFlag = true;
    this.createForm();

    this.getPurposeInfo();

    //初始化开始日期
    $('#startDate').datetimepicker({
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      stepping: 30,        //设置最小间隔分钟数
      ignoreReadonly: true,
      minDate:new Date()
    });

    //初始化预计结束时间
    $('#endDate').datetimepicker({
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      stepping: 30,        //设置最小间隔分钟数
      ignoreReadonly: true,
      minDate:new Date()
    });


    let startDate:any = this.routerInfo.snapshot.params['startdate'];
    let endDate: any = this.routerInfo.snapshot.params['enddate'];
    if(startDate && endDate){
      this.camForm.patchValue({
        starttimeToString:startDate,
        endtimeToString:endDate
      });
    }
  }

  createForm(){
    this.saveFlag = true;
    this.camForm =this.fb.group({
      // oid:'',
      subject:'',
      purpose:'',
      passengerNum:'',   //为number
      starttimeToString:'',
      endtimeToString:'',
      applicant:this.userId,
      contact:'',
      phone:'',
      startpoint:'',
      endpoint:'',
      shared:'',
      reason:'',
      passengers:'',
      res01:'',
      description:''
    });
  }

  //初始化用车性质
  getPurposeInfo(){
    this.camApplyService.getPurposes().then(res=>{
      this.purposes = res;
    });
  }

  //人员开窗选择
  btn_select_onclick(){
    this.udgTable.ngOnInit();
    this.udgShowModal();
  }

  //人员清空
  btn_clear(){
    this.camForm.patchValue({
      passengers:"",
      res01:""
    });
    $('#passengers').val("");
    $('#res01').val("");
    this.udgTable.checkAllUDG = [];
    this.udgTable.ngOnInit();
  }

  //数据卡控
  checkData(){
    let msg ="";
    let reg=/^[1][3,4,5,7,8][0-9]{9}$/;  //判断为手机号码
    let regexp=/^[0-9]\d*$/;;   //判断只能为整数
    if(!$("#subject").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入主题！\n");
    }
    if(!$("#purpose").val()){
      msg +=("请输入用车性质！\n");
    }
    if(!$("#passengerNum").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入同乘人数！\n");
    }
    if($("#passengerNum").val().replace(/^\s+|\s+$/g,"") && !regexp.test($("#passengerNum").val())){
      msg +=("同乘人数请填写正整数！\n");
    }
    if(!$("#starttime").val()){
      msg +=("请输入开始时间！\n");
    }
    if(!$("#endtime").val()){
      msg +=("请输入预计结束时间！\n");
    }
    if($("#starttime").val() && $("#endtime").val()
      && $("#starttime").val()>=$("#endtime").val()){
      msg +=("开始时间应该小于预计结束时间！\n");
    }
    if(!$("#contact").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入联系人！\n");
    }
    if(!$("#phone").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入手机号码！\n");
    }
    if($("#phone").val().replace(/^\s+|\s+$/g,"") && !reg.test($("#phone").val())){
      msg +=("请输入有效的11位手机号码\n");
    }
    if(!$("#startpoint").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入出发地！\n");
    }
    if(!$("#endpoint").val().replace(/^\s+|\s+$/g,"")){
      msg +=("请输入目的地！\n");
    }
    if(msg){
      alert(msg);
      return false;
    }else{
      return true;
    }
  }

  /**
   *  多选人员开窗
   */
  udgIsVisible = false;

  udgShowModal = () => {
    this.udgIsVisible = true;
  }

  udgHandleCancel = (e) => {
    // console.log(e);
    this.udgIsVisible = false;
  }

  //人员选中返回
  udgSearch(){
    let passengers = "";
    let userName = "";
    for(let i=0;i<this.udgTable.checkAllUDG.length;i++){
      passengers += this.udgTable.checkAllUDG[i].flag_id+";";
      userName += this.udgTable.checkAllUDG[i].id_name+";";
    }
    $("#passengers").val(passengers);
    $("#res01").val(userName);
    this.udgIsVisible = false;
  }

  //返回其他页面
  comeBack(){
    if(this.flag == "search"){
      this.router.navigate(["camSearch"],{queryParams:{userId:this.userId}});
    }else if(this.flag == "calendar"){
      this.router.navigate(["camCalendar"],{queryParams:{userId:this.userId}});
    }
  }

  //提交
  onSubmit(val:any){
    if(this.saveFlag) {
      if (this.checkData()) {
        this.saveFlag = false;
        this.camForm.patchValue({
          starttimeToString: $("#starttime").val(),
          endtimeToString: $("#endtime").val(), // starttime:$("#starttime").val() as string ,
          // endtime:$("#endtime").val() as string ,
          passengerNum: $("#passengerNum").val() as number,
          res01: $('#res01').val(),
          passengers: $('#passengers').val()
        });
        if (this._checked) {
          this.camForm.patchValue({
            shared: 1
          });
        } else {
          this.camForm.patchValue({
            shared: 0
          });
        }
        this.camApplyService.addApplication(this.camForm.value, this.child.fileoids).then(res => {
          console.log(res);
          if (res.code === 1) {
            alert(res.message);
            this.saveFlag = true;
            this.camForm.reset();
            //清空附件列表信息
            this.child.fileList = [];
            if (this.flag == "search") {
              this.router.navigate(["camSearch"], {queryParams: {userId: this.userId}});
            } else if (this.flag == "calendar") {
              this.router.navigate(["camCalendar"], {queryParams: {userId: this.userId}});
            }
          } else {
            alert(res.message);
          }
        });
      }
    }
  }
}
